package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.AgentReCommendCarActivity;
import com.gongpingjialoan.activity.car.BrowseActivity;
import com.gongpingjialoan.activity.car.BuyCarVipActivity;
import com.gongpingjialoan.activity.car.CollectActivity;
import com.gongpingjialoan.activity.car.EvalActivity;
import com.gongpingjialoan.activity.car.PushSettingActivity;
import com.gongpingjialoan.activity.car.SellCarHistoryActivity;
import com.gongpingjialoan.activity.car.SysRecomendCarActivity;
import com.gongpingjialoan.activity.loans.LoanHistoryActivity;
import com.gongpingjialoan.activity.tool.AppRecommendActivity;
import com.gongpingjialoan.activity.tool.ToolsActivity;
import com.gongpingjialoan.activity.vip.VIPDetailActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.VIPEb;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.view.GlideCircleTransform;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 我的界面 wang
 *
 * @author Administrator
 */
public class UserHomeFragment extends BaseFragment implements OnClickListener, PullToRefreshBase.OnRefreshListener<ScrollView> {


    private final int REQUEST_LOGIN = 0X098;

    private final int REQUEST_OPERATE = 0X088;
    private final int REQUEST_SELLCAR = 0X089;

    private static final int REQUEST_MY_MESSAGE = 0X092;
    private static final int REQUEST_AGENT = 0X093;
    private static final int REQUEST_ORDER = 0X094;
    private static final int REQUEST_SYSRECOM = 10086;

    private static final int REQUEST_LOAN = 0X195;

    private View view;

    private View logining_layout, no_login_view, car_type_view, order_record_rl, user_layout;

    private View toolView;

    private View messageView;

    private PullToRefreshScrollView mPullToRefreshScrollView;

    private NetDataJson detailNetDataJson, maintainNetDataJson, userInfoNetDataJson;

    private ImageView userImageView, settingImageView_White, settingImageView_Black;

    private String carType, contact_num;

    private TextView collectTextView, feedbackTextView;

    private TextView loginButton, userNameTextView;

    private TextView eval_num, plat_num, plat_num_small;

    private View browseView, sellCarView, evalView;

    private TextView car_type_TextView, crunchiesTextView;

    private RelativeLayout tools_layout5;

    private View sys_recomend_rl, agent_recommand_rl, subscribeV, operate_rl;

    View vip_info_layout;

    private RelativeLayout loan_info_layout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        action = "my";
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        view = inflater.inflate(R.layout.user_home_layout, container, false);
        user_layout = view.findViewById(R.id.user_layout);
        browseView = view.findViewById(R.id.liulan_id);
        userNameTextView = (TextView) view.findViewById(R.id.user_name);
        sellCarView = view.findViewById(R.id.sellcar_id);
        evalView = view.findViewById(R.id.guzhi_id);

        settingImageView_Black = (ImageView) view.findViewById(R.id.setting_b);
        logining_layout = view.findViewById(R.id.logining_main);
        no_login_view = view.findViewById(R.id.no_login_view);
        userImageView = (ImageView) view.findViewById(R.id.user_img);
        car_type_view = view.findViewById(R.id.car_type_view);
        toolView = view.findViewById(R.id.tools);
        messageView = view.findViewById(R.id.message_rl);
        car_type_TextView = (TextView) view.findViewById(R.id.car_type_id);
        crunchiesTextView = (TextView) view.findViewById(R.id.crunchies);
        settingImageView_White = (ImageView) view.findViewById(R.id.setting_w);
        loginButton = (TextView) view.findViewById(R.id.login_button);

//        registerTextView = (TextView) view.findViewById(R.id.register);
        collectTextView = (TextView) view.findViewById(R.id.collect);
        feedbackTextView = (TextView) view.findViewById(R.id.feedback);

        eval_num = (TextView) view.findViewById(R.id.eval_num);
        plat_num = (TextView) view.findViewById(R.id.plat_num);
        plat_num_small = (TextView) view.findViewById(R.id.small_plat_num);
        subscribeV = view.findViewById(R.id.subscribe);
        tools_layout5 = (RelativeLayout) view.findViewById(R.id.tools_layout5);
        tools_layout5.setOnClickListener(this);
        subscribeV.setOnClickListener(this);
        sellCarView.setOnClickListener(this);
        evalView.setOnClickListener(this);
        user_layout.setOnClickListener(this);
        crunchiesTextView.setOnClickListener(this);
        settingImageView_White.setOnClickListener(this);
        settingImageView_Black.setOnClickListener(this);
        browseView.setOnClickListener(this);
        loginButton.setOnClickListener(this);
//        registerTextView.setOnClickListener(this);
        collectTextView.setOnClickListener(this);
        feedbackTextView.setOnClickListener(this);
        //  userImageView.setOnClickListener(this);
        toolView.setOnClickListener(this);
        messageView.setOnClickListener(this);
        order_record_rl = view.findViewById(R.id.order_record_rl);
        order_record_rl.setOnClickListener(this);
        sys_recomend_rl = view.findViewById(R.id.sys_recomend_rl);
        sys_recomend_rl.setOnClickListener(this);
        operate_rl = view.findViewById(R.id.operate_id);
        operate_rl.setOnClickListener(this);
        agent_recommand_rl = view.findViewById(R.id.agent_recommand_rl);
        agent_recommand_rl.setOnClickListener(this);
        vip_info_layout = view.findViewById(R.id.vip_info_layout);
        vip_info_layout.setOnClickListener(this);

        loan_info_layout = (RelativeLayout) view.findViewById(R.id.loan_info_layout);
        loan_info_layout.setOnClickListener(this);
        mPullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.scroll_view);
        mPullToRefreshScrollView.setOnRefreshListener(this);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        if (GPJApplication.getInstance().isLogin()) {
            logining_layout.setVisibility(View.VISIBLE);
            no_login_view.setVisibility(View.GONE);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPullToRefreshScrollView.setRefreshing();
                }
            }, 400);
        } else {
            logining_layout.setVisibility(View.GONE);
            no_login_view.setVisibility(View.VISIBLE);
        }


//        UserManager mUserManager = new UserManager(getActivity());
//        mUserManager = mUserManager.LoadUserInfo();
//        view.findViewById(R.id.vip_img).setVisibility(mUserManager.is_vip() ? View.VISIBLE : View.GONE);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setLoginVis();
        UserManager mUserManager = new UserManager(getActivity());
        mUserManager = mUserManager.LoadUserInfo();
        view.findViewById(R.id.vip_img).setVisibility(mUserManager.is_vip() ? View.VISIBLE : View.GONE);

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        if (v == crunchiesTextView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", carType, System.currentTimeMillis(), 1f));
            ((MainActivity) getActivity()).changeToTopFragment(carType);
        } else if (v == settingImageView_Black || v == settingImageView_White) {
            intent.setClass(getActivity(), SettingActivity.class);
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_settings", System.currentTimeMillis(), 1.0f));
            startActivity(intent);
        } else if (v == loginButton) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "login", System.currentTimeMillis(), 1.0f));
            intent.setClass(getActivity(), LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN);
        } else if (v == feedbackTextView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_feedBack", System.currentTimeMillis(), 1.0f));
            FeedbackAPI.openFeedbackActivity();
            if (GPJApplication.getInstance().isLogin()) {
                UserManager userManager = new UserManager().LoadUserInfo();
                String phone = userManager.getPhone();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("phone", phone);
                } catch (JSONException e) {
                }
                FeedbackAPI.setAppExtInfo(jsonObject);
            }
        } else if (v == toolView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "tools", System.currentTimeMillis(), 1.0f));
            intent.setClass(getActivity(), ToolsActivity.class);
            startActivity(intent);
        } else if (v == messageView) {
            if (GPJApplication.getInstance().isLogin()) {
                //进入会话列表页面
//                StepMonitor.getInstance().addMonitor(new Monitor("click", "my_notifications", System.currentTimeMillis(), 1.0f));
//                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_MY_MESSAGE);
            }
        } else if (v == browseView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_viewRecord", System.currentTimeMillis(), 1.0f));
            startActivity(new Intent(getActivity(), BrowseActivity.class));
        } else if (v == collectTextView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_likeRecord", System.currentTimeMillis(), 1.0f));
            startActivity(new Intent(getActivity(), CollectActivity.class));
        } else if (v == evalView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_evalRecord", System.currentTimeMillis(), 1.0f));
            startActivity(new Intent(getActivity(), EvalActivity.class));
        } else if (v == sellCarView) {
            if (GPJApplication.getInstance().isLogin()) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "my_sellRecord", System.currentTimeMillis(), 1.0f));
                startActivity(new Intent(getActivity(), SellCarHistoryActivity.class));
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_SELLCAR);
            }
        } else if (v == subscribeV) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_subscribeRecord", System.currentTimeMillis(), 1f));
            startActivity(new Intent(getActivity(), PushSettingActivity.class));
        } else if (v == tools_layout5) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "friendApp", System.currentTimeMillis(), 1f));
            startActivity(new Intent(getActivity(), AppRecommendActivity.class));
        } else if (v == sys_recomend_rl) {

            if (GPJApplication.getInstance().isLogin()) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "system_recommend_car", System.currentTimeMillis(), 1f));


                UserManager mUserManager = new UserManager(getActivity());
                mUserManager = mUserManager.LoadUserInfo();
                //如果没有设置vip筛选条件,先跳转到设置页面
                if (!mUserManager.isBuy_car_recommend_flag()) {
                    Intent it = new Intent(getActivity(), BuyCarVipActivity.class);
                    it.putExtra("from", "userhome");
                    startActivity(it);
                } else {
                    startActivity(new Intent(getActivity(), SysRecomendCarActivity.class));
                }
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_SYSRECOM);
            }

        } else if (v == agent_recommand_rl) {
            if (GPJApplication.getInstance().isLogin()) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "my_dealerRecommendList", System.currentTimeMillis(), 1f));
                startActivity(new Intent(getActivity(), AgentReCommendCarActivity.class));
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_AGENT);
            }
        } else if (v == operate_rl) {
            if (GPJApplication.getInstance().isLogin()) {
                Intent it = new Intent(getActivity(), OperateActivity.class);
                it.putExtra("contract_num", contact_num);
                startActivity(it);
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_OPERATE);
            }
        } else if (v == order_record_rl) {
            if (GPJApplication.getInstance().isLogin()) {
                startActivity(new Intent(getActivity(), OrderActivity.class));
                StepMonitor.getInstance().addMonitor(new Monitor("click", "my_orderList", System.currentTimeMillis(), 1f));
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_ORDER);
            }
        } else if (v == user_layout) {
            intent.setClass(getActivity(), UserCenterActivity.class);
            startActivity(intent);
        } else if (v == vip_info_layout) {
            intent.setClass(getActivity(), VIPDetailActivity.class);
            intent.putExtra("from","my_vipRight");
            startActivity(intent);
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_vipRight", System.currentTimeMillis(), 1f));
        }else if(v == loan_info_layout){
            if (GPJApplication.getInstance().isLogin()) {
                startActivity(new Intent(getActivity(), LoanHistoryActivity.class));
            } else {
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_LOAN);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            UserManager mUserManager = new UserManager(getActivity());
            mUserManager = mUserManager.LoadUserInfo();
            view.findViewById(R.id.vip_img).setVisibility(mUserManager.is_vip() ? View.VISIBLE : View.GONE);
        }
    }

    public void refresh() {
        if (isAdded()) {
            car_type_view.setVisibility(View.GONE);
            if (GPJApplication.getInstance().isLogin()) {
                logining_layout.setVisibility(View.VISIBLE);
                no_login_view.setVisibility(View.GONE);
                mPullToRefreshScrollView.setRefreshing();
            } else {
                logining_layout.setVisibility(View.GONE);
                no_login_view.setVisibility(View.VISIBLE);

                eval_num.setVisibility(View.GONE);
                plat_num.setVisibility(View.GONE);
                plat_num_small.setVisibility(View.GONE);
            }
        }
    }


    private void getMyCarDetail() {
        eval_num.setVisibility(View.GONE);
        plat_num.setVisibility(View.GONE);
        plat_num_small.setVisibility(View.GONE);
        UserManager userManager = new UserManager().LoadUserInfo();
        String username = userManager.getUser();
        if (!TextUtils.isEmpty(username)) {
            userNameTextView.setText(username);
        } else {
            userNameTextView.setText("公平价用户");
        }
        String avatar = userManager.getAvatar();
        if (!TextUtils.isEmpty(avatar)) {
            Glide.with(this).load(avatar).placeholder(R.drawable.my_person).transform(new GlideCircleTransform(getActivity())).into(userImageView);
        } else {
            userImageView.setImageResource(R.drawable.my_person);
        }
        getUserInfo();
    }


    private void getUserInfo() {
        if (userInfoNetDataJson == null) {
            userInfoNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                    mPullToRefreshScrollView.onRefreshComplete();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    try {
                        contact_num = json.getString("contact_record_count");
                        eval_num.setText("估过" + json.getString("eval_record_count") + "辆车");
                        String num = json.getString("sell_car_reply_count");
                        eval_num.setVisibility(View.VISIBLE);
                        if (!"0".equals(num)) {
                            plat_num.setText("有" + num + "个平台给予反馈");
                            plat_num_small.setText(num);
                            plat_num.setVisibility(View.VISIBLE);
                            plat_num_small.setVisibility(View.VISIBLE);
                        } else {
                            plat_num.setVisibility(View.GONE);
                            plat_num_small.setVisibility(View.GONE);
                        }


                        JSONObject info = json.getJSONObject("view_car_price_info");
                        if (info.length() != 0) {
                            carType = info.getString("car_type");
                            String carTypeString = info.getString("car_type_str");
                            car_type_TextView.setText("看过" + info.getString("all_count") +
                                    "辆车 其中" + info.getString("car_count")
                                    + "辆车都是" + carTypeString);
                            crunchiesTextView.setText(carTypeString + "榜单");
                            car_type_view.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "用户数据异常，请稍后再试！", Toast.LENGTH_SHORT).show();
                    } finally {
                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                }
            });
        }
        userInfoNetDataJson.setUrl(API.user_info);
        userInfoNetDataJson.request("get");
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (detailNetDataJson != null) {
            detailNetDataJson.cancelTask();
            detailNetDataJson = null;
        }
        if (maintainNetDataJson != null) {
            maintainNetDataJson.cancelTask();
            maintainNetDataJson = null;
        }
        if (userInfoNetDataJson != null) {
            userInfoNetDataJson.cancelTask();
            userInfoNetDataJson = null;
        }
    }


//    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {

        String label =
                "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

        getMyCarDetail();
    }

    private void setLoginVis() {
        if (GPJApplication.getInstance().isLogin()) {
            logining_layout.setVisibility(View.VISIBLE);
            no_login_view.setVisibility(View.GONE);
        } else {
            logining_layout.setVisibility(View.GONE);
            no_login_view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOGIN:
                    setLoginVis();
                    break;
                case REQUEST_OPERATE:
                    Intent it = new Intent(getActivity(), OperateActivity.class);
                    it.putExtra("contract_num", contact_num);
                    startActivity(it);
                    break;
                case REQUEST_SELLCAR:
                    setLoginVis();
                    StepMonitor.getInstance().addMonitor(new Monitor("click", "my_sellRecord", System.currentTimeMillis(), 1.0f));
                    startActivity(new Intent(getActivity(), SellCarHistoryActivity.class));
                    break;
                case REQUEST_AGENT:
                    setLoginVis();
                    StepMonitor.getInstance().addMonitor(new Monitor("click", "my_dealerRecommendList", System.currentTimeMillis(), 1f));
                    startActivity(new Intent(getActivity(), AgentReCommendCarActivity.class));
                    break;
                case REQUEST_ORDER:
                    setLoginVis();
                    StepMonitor.getInstance().addMonitor(new Monitor("click", "my_orderList", System.currentTimeMillis(), 1f));
                    startActivity(new Intent(getActivity(), OrderActivity.class));
                    break;
                case REQUEST_MY_MESSAGE:
                    setLoginVis();
//                    StepMonitor.getInstance().addMonitor(new Monitor("click", "my_chatNotification", System.currentTimeMillis(), 1.0f));
//                    startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                    break;
                case REQUEST_LOAN:
                    setLoginVis();
                    startActivity(new Intent(getActivity(), LoanHistoryActivity.class));
                case REQUEST_SYSRECOM:
                    setLoginVis();

                    UserManager mUserManager = new UserManager(getActivity());
                    mUserManager = mUserManager.LoadUserInfo();
                    //如果没有设置vip筛选条件,先跳转到设置页面
                    if (!mUserManager.isBuy_car_recommend_flag()) {
                        Intent buyit = new Intent(getActivity(), BuyCarVipActivity.class);
                        buyit.putExtra("from", "userhome");
                        startActivity(buyit);
                    } else {
                        startActivity(new Intent(getActivity(), SysRecomendCarActivity.class));
                    }
                    break;
                default:
                    break;
            }
        }

    }

    @Subscribe
    public void onEventMainThread(VIPEb VIPEb) {
        view.findViewById(R.id.vip_img).setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}